import { cycleDate } from '~/util'
import ScrollLoadEvent from '~/util/scrollLoadEvent'
export default {
  data () {
    return {
      list: [],
      pageNo: 1,
      pageSize: 20,
      total: 0,
      cycleDate,
      firstLoading: true,
      scrollLoadEvent: null
    }
  },

  created () {
    this.getNotifications()
  },

  mounted () {
    this.scrollLoadEvent = new ScrollLoadEvent(
      this.getNotifications.bind(this, true)
    )
    this.$nextTick(() => {
      this.scrollLoadEvent.bindScrollEvent()
    })
  },

  methods: {
    /**
     * 查询用户消息集合
     * @param { Boolean } isScroll 是否在滚动到底部的时候触发的请求
     */
    async getNotifications (isScroll) {
      if (isScroll) {
        this.pageNo++
        this.scrollLoadEvent.loadState = false
      }
      try {
        const requestParams = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          itemType: this.itemType
        }
        const { data } = await this.$axios.post(
          '/gimishare/api/v1/messages',
          requestParams
        )
        this.list.push(...data.list)
        if (isScroll) {
          if (this.pageNo >= Math.ceil(data.total / this.pageSize)) {
            this.scrollLoadEvent.loadState = false
          } else {
            this.scrollLoadEvent.loadState = true
          }
        }
      } catch (error) {
        if (isScroll) {
          this.scrollLoadEvent.loadState = true
        }
      } finally {
        this.firstLoading = false
      }
    }
  },

  beforeDestroy () {
    this.scrollLoadEvent.removeScrollEvent()
  }
}
